package com.zl.learning.arithmetic.my;

import com.zl.learning.arithmetic.util.SortUtil;

import java.util.Arrays;

public class HeapSort {
    private static int[] a = SortUtil.getRandomArray();
//    private static int[] a = {4, 6, 8, 5, 9};

    private static void heapSort(int[] a) {
        for (int i = a.length / 2 - 1; i >= 0; i--) {
            adjustHeap(a, i, a.length);
        }
        for (int i = a.length - 1; i > 0; i--) {
            swap(a, 0, i);
            adjustHeap(a, 0, i);
        }
    }

    private static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }

    private static void adjustHeap(int[] a, int i, int length) {
        int tmp = a[i];
        for (int j = i * 2 + 1; j < length; j = j * 2 + 1) {
            if (j + 1 < length && a[j] < a[j + 1]) {
                j++;
            }
            if (a[j] > tmp) {
                a[i] = a[j];
                i = j;
            } else {
                break;
            }
        }
        a[i] = tmp;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(a));
        heapSort(a);
        System.out.println(Arrays.toString(a));
    }
}
